package cz.cvut.fel.gfupan.gui.action;

import cz.cvut.fel.gfupan.gui.component.AutoCompleteBox;
import cz.cvut.fel.gfupan.gui.util.AutoCompleteItem;
import cz.cvut.fel.gfupan.gui.util.AutoCompleteList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class FindAction extends KeyAdapter implements ActionListener {

    private AutoCompleteBox combo;

    public FindAction(AutoCompleteBox root) {
        this.combo = root;
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        showIt(combo.getEditor().getItem().toString());
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_F1 || code == KeyEvent.VK_F2 || code == KeyEvent.VK_F3 || code == KeyEvent.VK_F4 || code == KeyEvent.VK_F5
                || code == KeyEvent.VK_F6 || code == KeyEvent.VK_F7) {
            return;
        }
        if (code == KeyEvent.VK_ENTER) {
            showIt(combo.getEditor().getItem().toString());
        }
    }

    private void showIt(String a) {
        AutoCompleteItem result = AutoCompleteList.find(new AutoCompleteItem(a), combo.items());
        if (result != null) {
            combo.getWindow().showElementByMeasureAndId(result.measure, result.tab, result.id);
        }
    }
}